package com.sdyeda.readiot.fx;

import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.sdyeda.readiot.data.SetSave;
import com.sdyeda.readiot.data.SetSaveService;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonBar;
import javafx.scene.control.ButtonType;
import javafx.scene.control.TableView;
import javafx.stage.Stage;

@Component
public class SetSaveController {
	private Stage stage;
	
	@FXML
	private Button btnAdd,btnEdit,btnDel,btnClose;
	
	@FXML
	private TableView<SetSave> tvList;
	
	@Autowired
	private SetSaveService setSaveService;
	
	@FXML
	public void initialize() {
		
		//添加按钮
		btnAdd.setOnAction(Event ->{
			Stage addstage = new Stage();
			new SetSaveDetailWindow(addstage, stage,null);
			addstage.showAndWait();
			RefrushList();
				
		});
		//修改
		btnEdit.setOnAction(Event->{
			if (tvList.getSelectionModel().getSelectedCells().size() > 0) {
				SetSave save = tvList.getItems().get(tvList.getSelectionModel().getSelectedCells().get(0).getRow());
				Stage editstage = new Stage();
				new SetSaveDetailWindow(editstage, stage, save);
				editstage.showAndWait();
				RefrushList();
			}
			else {
				new Alert(AlertType.INFORMATION, "请先选择要修改的记录").show();
			}
		});
		
		//删除
		btnDel.setOnAction(Event->{
			if (tvList.getSelectionModel().getSelectedCells().size() > 0) {
				
				Optional<ButtonType> bt = new Alert(AlertType.CONFIRMATION,"确定要删除吗？").showAndWait();
				if(bt.get().getButtonData()==ButtonBar.ButtonData.OK_DONE) {
					SetSave save = tvList.getItems().get(tvList.getSelectionModel().getSelectedCells().get(0).getRow());
					setSaveService.delete(save);
					RefrushList();
				}
			}
			else {
				new Alert(AlertType.INFORMATION, "请先选择要删除的记录").show();
			}
		});
		//关闭
		btnClose.setOnAction(Event->{
			stage.close();
		});

		RefrushList();
		
	}

	private void RefrushList() {
		
		List<SetSave> list = setSaveService.findAll();
		ObservableList<SetSave> tvlist = FXCollections.observableArrayList(list);
		tvList.setItems(tvlist);
		tvList.refresh();
	}

	public Stage getStage() {
		return stage;
	}

	public void setStage(Stage stage) {
		this.stage = stage;
	}
}
